package com.baiyue.utils;

import com.jcraft.jsch.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 伍波
 * @date 2023/8/8 20:09
 */
public class FtpUtil {

    private static ChannelSftp getChannel(String host, int port, String userName, String password) throws JSchException {
        JSch jsch = new JSch();

        //->ssh root@host:port
        Session sshSession = jsch.getSession(userName, host, port);
        //密码
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        return (ChannelSftp) channel;
    }

    public static void uploadFile(File file, String ftpHost, int ftpPort, String ftpUsername, String ftpPassword, String ftpRootPath,String fileName){
        ChannelSftp sftp = null;
        try {
            sftp = getChannel(ftpHost, ftpPort, ftpUsername, ftpPassword);
            sftp.put(new FileInputStream(file), ftpRootPath+fileName);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (sftp != null) {
                sftp.quit();
                sftp.exit();
            }
        }
    }
}
